package com.maslyk.invitation.service.email;

import java.util.Date;
import java.util.List;

import javax.mail.Flags.Flag;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Store;
import javax.mail.internet.InternetAddress;

import com.maslyk.invitation.entitybean.Comment;
import com.maslyk.invitation.entitybean.Order;
import com.maslyk.invitation.entitybean.Salesman;
import com.maslyk.invitation.service.PersistenceService;
import com.maslyk.invitation.to.OrderSearchCondition;

/**
 *
 * @author kris
 */
public class EmailProcessingService
{
	private PersistenceService persistenceService;
	
    public void orderEmailProcess() throws Exception
    {
        Store store = MessagingEmailService.getMessagesStore();

        // Open the folder
        Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_WRITE);

        // Get the messages from the server
        Message [] msgs = inbox.getMessages();

        if(msgs.length == 0)
            return;

        MessagingEmailService emailService = new MessagingEmailService();

        Salesman automat = persistenceService.login("automat", "automat");

        for(Message msg : msgs)
        {
            if(msg.getSubject() == null || msg.getSubject().trim().length() == 0)
                continue;
            
            InternetAddress[] from = (InternetAddress[]) msg.getFrom();

            OrderSearchCondition osc = new OrderSearchCondition();
            
            osc.setNumber(msg.getSubject());
            List<Order> list = persistenceService.searchOrders(osc);

            if(list.size() > 1)
                emailService.sendMessage(from[0].getAddress(), "Istnieje wiecej niz jedno takie zamowienie", "Blad wyszukania zamowienia: "+ msg.getSubject());
            else if(list.size() < 1)
                emailService.sendMessage(from[0].getAddress(), "Zweryfikuj czy zamowienie o numerze: " + msg.getSubject() + " istnieje w systemie.", "Nie znaleziono zamowienia: "+ msg.getSubject());
            else
            {
            	IEmailContentProcess transformService = MIMEServiceFactory.getMIMEService(msg.getContentType());
            	String content = transformService.getContent(msg.getContent());
                
                Order foundOrder = list.get(0);
                Comment cmnt = new Comment();
                cmnt.setOrder(foundOrder);
                cmnt.setRegistrationDate(new Date());
                cmnt.setNote(content);
                cmnt.setSalesmanID(automat);

                foundOrder.getCommentList().add(cmnt);
                persistenceService.saveOrder(foundOrder);

                emailService.sendMessage(from[0].getAddress(), "Tresc emaila:\n\n "+ content, "Dodano email do zamowienia: "+ msg.getSubject());
            }
            msg.setFlag(Flag.DELETED, true);
        }

        // Close the connection
        // and remove the messages from the server
        inbox.close(true);
        store.close();
    }

	public void setPersistenceService(PersistenceService persistenceService) {
		this.persistenceService = persistenceService;
	}
}
